package notice.consumer;

import com.alibaba.fastjson.JSON;
import com.rabbitmq.client.Channel;
import common.SnowflakeIdWorker;
import lombok.extern.slf4j.Slf4j;
import mq.dao.mapper.MqMessageCumulateMapper;
import mq.domain.MqMessageCumulate;
import mq.service.IMqMailService;
import mq.service.impl.MqMailServiceImpl;
import notice.config.MQDeductionConfig;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Date;
import java.util.Map;
import java.util.Objects;

/**
 * @description: 消费"扣款结果通知"死信队列中的消息
 * @author: zk
 * @since: 2022-08-16 15:09
 */
@Slf4j
@Component
public class DeductionNoticeDeathQueueConsumer {
    @Resource
    private MqMessageCumulateMapper mqMessageCumulateMapper;
    @Resource
    private MessageConverter messageConverter;
    @Resource
    private IMqMailService mqMailService;
    //@Resource
    //private MailServiceUtil mailServiceUtil;
    //@Value("${mail.toEmil}")
    //private String toEmil;

    @RabbitListener(queues = {MQDeductionConfig.DEATH_QUEUE_DEDUCTION_NOTICE})
    public void consumeMessage(Message message, Channel channel) throws IOException {
        log.info("扣款结果通知死信队列收到消息 message={}",message);
        try {
            Object msg = messageConverter.fromMessage(message);
            // 消息入库
            MessageProperties messageProperties = message.getMessageProperties();
            String messageId = messageProperties.getMessageId();
            Map<String, Object> headers = messageProperties.getHeaders();
            Object reason = headers.get("x-first-death-reason");
            MqMessageCumulate mqMessageCumulate = MqMessageCumulate.builder()
                    .messageId(StringUtils.isNotBlank(messageId) ? messageId : String.valueOf(SnowflakeIdWorker.nextID()))
                    .message(JSON.toJSONString(msg))
                    .status(MqMessageCumulate.STATUS_DEFAULT)
                    .cause((Objects.nonNull(reason)) ? String.valueOf(reason) : "扣款通知消息堆积")
                    .busiNo(MqMessageCumulate.BUSI_NO_DEDUCTION)
                    .createTime(new Date())
                    .updateTime(new Date())
                    .build();
            mqMessageCumulateMapper.insert(mqMessageCumulate);

            // 邮件预警
            mqMailService.addRecord(mqMessageCumulate.getMessageId(), MqMailServiceImpl.TYPE_MESSAGE_CUMULATE);

            // 手动签收
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (Exception e) {
            log.error("扣款结果通知死信队列消费者处理失败! message={}",message,e);
            // 手动签收
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);

            // 立即邮件预警
            //mailServiceUtil.sendMail(toEmil, "扣款通知死信队列消费者处理异常 message=" + JSONObject.toJSONString(message) + " 请尽快核对处理",
            //        "【扣款通知死信队列】消费异常预警");

        }
    }

} 